const app = getApp();
const AJAX = app.$ajax,
  $wx = app.$wx;

Page({
  onLoad(options){
    this.setData({
      goodsId: options.detail_id
    }, callback => {
      this.getGoodDetail();
    });
  },

  onShareAppMessage(){

  },

  collect(e){
    let id = e.currentTarget.dataset.id;
    this.collectGood(id);
  },

  getSpec(e){
    let td = this.data,
     ed = e.currentTarget.dataset;

    td.spec.spec_attr[ed.pindex].activeItem = ed.cindex;
     this.setData({
       spec: td.spec
     });
  },

  buy(){
    this.createOrder();
  },

  /**
   * 获取商品详情
   * @param id
   * */ 
  getGoodDetail(id){
    let td = this.data;
    AJAX.goodDetail({
      loadType: 'bar',
      goods_id: td.goodsId
    }).then(([status, res, msg]) => {
      if(status){
        this.setData({
          detail: res.detail
        });

        if (res.specData && Object.keys(res.specData).length > 0){
          let spec = res.specData;
          spec.spec_attr.forEach(item => {
            item.activeItem = 0;
          });

          this.setData({ spec });
        }
      }else{
        $wx.shosToast(msg);
      }
    });
  },

  /**
   * 收藏商品
   * @param goods_id
   * */
  collectGood(id){
    let _this = this, td = _this.data;
    AJAX.collectGood({
      loadType: 'bar',
      goods_id: id
    }).then(([status, res, msg]) => {
      $wx.showToast(msg, {
        success(){
          td.detail.is_conllect = res.is_conllect;
          _this.setData({
            detail: td.detail
          });
        }
      }); 
    });
  },

  /**
   * 加入购物车
   * @param goods_id
   * @param goods_num
   * @param goods_sku_id
   * */ 
  addCart(e){
    let td = this.data,
      goods_sku_id = [];

    td.spec && td.spec.spec_attr.map(item => {
      goods_sku_id.push(item.spec_items[item.activeItem].item_id);
    });

    AJAX.addCart({
      loadType: 'default',
      loadMsg: '加入购车中...',
      goods_id: td.goodsId,
      goods_sku_id: JSON.stringify(goods_sku_id || []),
      goods_num: 1,
    }).then(([status, res, msg]) => {
      $wx.showToast(msg);
    });
  },

  createOrder() {
    let td = this.data, chicun, caizhi;
    td.spce && td.spec.spec_attr.map(item => {
      if(item.group_name === '尺寸'){
        chicun = item.spec_items[item.activeItem].item_id;
      }
      if(item.group_name === '材质'){
        caizhi = item.spec_items[item.activeItem].item_id;
      }
    });
    AJAX.createOrder({
      loadType: 'default',
      loadMsg: '加载中...',
      type: 2,
      goods_id: td.goodsId,
      goods_num: 1,
      chicun,
      caizhi
    }).then(([status, res, msg]) => {
      if (status) {
        wx.setStorageSync("orderDetail", res);
        wx.navigateTo({
          url: '/pages/subpage/order/detail/detail'
        })
      } else {
        $wx.showToast(msg);
      }
    });
  },
});